<template>
  <div>
    <!-- 面包屑 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
     <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
     <el-breadcrumb-item>用户管理</el-breadcrumb-item>
     <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!--添加卡片  -->
  <el-card>
    <!-- 添加搜索框 -->
   <el-row :gutter='30'>
     <el-col :span='7'>
       <el-input placeholder="请输入内容"  clearable v-model="queryinfo.query" @clear='getuserlist()'>
      <el-button slot="append"  icon="el-icon-search" @click="getuserlist()"></el-button>
  </el-input>
     </el-col>
     <el-col :span='4'>
       <el-button type='primary' @click="addnewrole=true">添加用户</el-button>
     </el-col>
   </el-row>
   <!-- 添加表格 -->
   <el-table  stripe  border :data='userList' style="width: 100%">
     <el-table-column type='index'  label='#' ></el-table-column>
     <el-table-column prop='username' label='姓名' ></el-table-column>
     <el-table-column prop='email' label='邮箱'></el-table-column>
     <el-table-column prop='mobile' label='电话' ></el-table-column>
     <el-table-column prop='role_name' label='角色' ></el-table-column>
     <el-table-column  label='状态' >
     <template slot-scope='scope'>
          <el-switch
           v-model="scope.row.mg_state"
          active-color="#13ce66"
           @change='currentstate(scope)'
           >
        </el-switch>
     </template>
     </el-table-column>
     <!-- 表格操作按钮 -->
     <el-table-column  label='操作' width='180' >
       <template slot-scope='scope'>
          <el-button type="primary" icon="el-icon-edit" size='mini' @click="compile(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size='mini' @click="removerole(scope.row)"></el-button>
           <el-tooltip effect="dark" content="角色管理" placement="top" :enterable='false'>
          <el-button type="warning" icon="el-icon-s-tools" size='mini' @click="adminroles(scope.row)" ></el-button>
         </el-tooltip>
       </template>
     </el-table-column>
   </el-table>
   <!-- 添加分页栏 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryinfo.pagenum"
      :page-sizes="[1,2,5,10]"
      :page-size="queryinfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
  <!-- 添加新用户对话框 -->
  <el-dialog
   title="添加新用户"
  :visible.sync="addnewrole"
  width="50%"
  @close='resetaddfrom'>
  <el-form width='80%' :rules="rules" :model='addnewinfo' ref='addnewfrom'>
    <el-form-item label='用户名' label-width='65px' prop='username'>
      <el-input v-model='addnewinfo.username'></el-input>
    </el-form-item>
    <el-form-item label='密码' label-width='67px' prop='password'>
      <el-input  v-model='addnewinfo.password'></el-input>
    </el-form-item>
    <el-form-item label='邮箱' label-width='67px' prop='email' >
      <el-input  v-model='addnewinfo.email'></el-input>
    </el-form-item>
    <el-form-item label='手机' label-width='67px' prop='mobile'>
      <el-input  v-model='addnewinfo.mobile'></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addnewrole = false" >取 消</el-button>
    <el-button type="primary" @click="fromsubmit">确 定</el-button>
  </span>
</el-dialog>
<!--修改用户信息对话窗  -->
<el-dialog
  title="修改用户信息"
  :visible.sync="rolesedit"
  width="50%"
  :model='addnewinfo' @close='resetsfrom'>
   <el-form width='80%' :rules="rules" :model='editinfo' ref='editform'>
    <el-form-item label='用户名'  label-width='65px' prop='username'>
      <el-input v-model='editinfo.username'  :disabled="true"></el-input>
    </el-form-item>
    <el-form-item label='邮箱' label-width='67px' prop='email' >
      <el-input  v-model='editinfo.email'></el-input>
    </el-form-item>
    <el-form-item label='手机' label-width='67px' prop='mobile'>
      <el-input  v-model='editinfo.mobile'></el-input>
    </el-form-item>
  </el-form>
   <span slot="footer" class="dialog-footer">
    <el-button @click="rolesedit = false">取 消</el-button>
    <el-button type="primary" @click="editsubmit">确 定</el-button> 
    </span>
</el-dialog>
<!-- 角色管理 -->
<el-dialog
  title="角色管理"
  :visible.sync="rolesadmin"
  width="50%"
  @close='clearnselect'>
  <div>
    <p>用户名:<span>{{userinfo.username}}</span></p>
    <p>角色:<span>{{userinfo.role_name}}</span></p>
    <P>分配新角色：
     <el-select v-model="rolesadmininfo" placeholder="请选择">
     <el-option

      v-for="item in rolesadminlist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="rolesadmin = false">取 消</el-button>
    <el-button type="primary" @click="addrolesmadin">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
  export default {
    name:'user',
    data () {
      return {
        queryinfo:{
          query:'',
          pagenum:1,
          pagesize:2
        },
        userList:[],
        total:0,
        editid:0,
        addnewrole:false,
        rolesedit:false,
        addnewinfo:{
          username:'',
          password:'',
          email:'',
          mobile:''
        },
        editinfo:{
          username:'',
          email:'',
          mobile:''
        },
        rolesadmin:false,
        rolesadminlist:[],
        userinfo:{},
        rolesadmininfo:'',
        rules:{
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入你的邮箱', trigger: 'blur' },
            {pattern:/^[a-zA-Z0-9&%}]{2,}@[a-zA-Z0-9&%]{1,}\.[a-zA-Z0-9&%]{2,}$/, message:'你输入的邮箱不合法',trigger: 'blur'}
          ],
          mobile:[
          { required: true, message: '请输入你的电话号码', trigger: 'blur' },
          {pattern:/^[0-9-]{6,}$/, message:'你输入的电话号码不合法',trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      async getuserlist(){
     const  resulte=  await this.$http.get('users',{params:this.queryinfo})
  
      if(resulte.data.meta.status !==200){
       return this.$message({showClose: true,message: `获取用户列表失败了`,type: 'error'})
     }
       this.userList=resulte.data.data.users
       this.total=resulte.data.data.total  
    },
    handleSizeChange(val){
       this.queryinfo.pagesize=val
       this.getuserlist()
    },
    handleCurrentChange(val){
     this.queryinfo.pagenum=val
     this.getuserlist()
    },
    // 修改用户状态
    async currentstate(userinfo){
    let result= await this.$http.put(`users/${userinfo.row.id}/state/${userinfo.row.mg_state}`)
    // console.log(result)
    if(result.data.meta.status !==200){
      userinfo.row.mg_state = !userinfo.row.mg_state
      return  this.$message({showClose: true,message: `修改用户状态失败`,type: 'error'})
    }
    this.$message({showClose: true,message: `修改用户状态成功`,type: 'success'})
    },
    //添加新用户
    async fromsubmit(){
    let validata= await this.$refs.addnewfrom.validate()
    if(!validata) return
    let result= await this.$http.post('users', this.addnewinfo)
    console.log(result)
    this.addnewrole=false
    if(result.data.meta.status !=201){
      return this.$message({showClose: true,message: `${result.data.meta.msg}`,type: 'error'})
    }
     this.$message({showClose: true,message: `添加新用户成功`,type: 'success'})
    this.getuserlist()
    },
    //删除用户
    async removerole(newsinfo){
    //如果要引入确认小心警告框首先在入口函数中全局挂载
    /*
    import { MessageBox } from 'element-ui';
    挂载全局
    Vue.prototype.$MessageBox=MessageBox.confirm
    */ 
    let comfigResult= await this.$MessageBox('此操作将永久删除该用户的信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        /*
        弹出框如果用户点击确定  comfigResult值为confirm
        弹出框如果用户点击取消  comfigResult值为cancel
        */
       if(comfigResult !='confirm'){
         return  this.$message('取消删除成功！');
       }
    let result=  await this.$http.delete(`users/${newsinfo.id}`)
    if(result.data.meta.status !=200){
      return this.$message({showClose: true,message: `删除用户失败！`,type: 'error'})
    }
   this.$message({showClose: true,message: '删除用户成功！',type: 'success'}); 
    this.getuserlist()
    },
    //重置添加用户表单信息
    resetaddfrom(){
       this.$refs.addnewfrom.resetFields()
    },
    //弹出修改用户表单
  async compile(userinfo){
       this.editinfo.username=userinfo.username
       this.editinfo.email=userinfo.email
       this.editinfo.mobile=userinfo.mobile
      this.rolesedit=true
      this.editid=userinfo.id
    },
    async editsubmit(){
     const validate= await this.$refs.editform.validate()
    if(!validate) return
       const result=await this.$http.put(`users/${this.editid}`,{email:this.editinfo.email,mobile: this.editinfo.mobile})
     if(result.data.meta.status !=200){return  this.$message({showClose: true,message: `修改用户信息失败`,type: 'error'})}
   this.$message({showClose: true,message: `修改用户信息成功`,type: 'success'})
    this.getuserlist()
      this.rolesedit = false
    },
    resetsfrom(){
      this.editform.resetFields()
    },
    //角色管理
    async adminroles(userinfo){
      this.userinfo=userinfo
      let result =await this.$http.get('roles')
      // console.log(result)
      if(result.data.meta.status !=200){return this.$message({showClose: true,message: `获取角色管理信息失败`,type: 'error'}) }
      this.rolesadminlist=result.data.data
      this.rolesadmin=true
    },
    //更换角色功能
   async  addrolesmadin(){
      if(!this.rolesadmininfo){
        return  this.$message({showClose: true,message: `请选择你要分配的角色`,type: 'error'})
      }
      let result = await this.$http.put(`users/${this.userinfo.id}/role`,{rid:this.rolesadmininfo})
      if(result.data.meta.status !=200){return {showClose: true,message: `分配的角色失败`,type: 'error'}}
      this.$message({showClose: true,message: `分配的角色成功`,type: 'success'})
    this.getuserlist()
    this.clearnselect()
      this.rolesadmin=false
    },
    //清空分配角色下拉框
    clearnselect(){
      this.rolesadmininfo=''
      this.rolesadminlist=[]
    }
    },
    created () {
     this.getuserlist()
    }
  }
</script>

<style lang="less" scoped>
  .el-breadcrumb{
    margin-bottom: 15px;
  }
  .el-table{
    margin-top: 15px;
  }
  .el-pagination{
    margin-top:15px;
  }
  .el-form-item{
    margin-top: 35px;
  }
  p{
    margin-top: 30px;
    font-size: 19px;
    span{
      margin-left:50px;
      font-weight: bold;

    }
  }
  .el-select{
    margin-top: 10px;
  }
</style>